import { getbanner, upBanner } from '@/api/banner'
import { get_requset } from '@/api/publicRequest'
import { apiHomBlogType } from '@/routerConfig'
const state = {
  bannerList: [],
  blogTypeLists: []
}

const mutations = {
  SET_BANNERLIST: (state, bannerList) => {
    state.bannerList = bannerList
  },
  SET_BLOGTYPE: (state, blogTypeList) => {
    state.blogTypeLists = blogTypeList
  }
}
const actions = {
  getBannerList({ commit }) {
    return new Promise((resolve, reject) => {
      getbanner().then((res) => {
        const result = res.data
        if (!result) reject()
        commit('SET_BANNERLIST', [result.background, ...result.banner])
        resolve()
      }).catch((e) => {
        reject(e)
      })
    })
  },
  getBlogType({ commit }) {
    return new Promise((resolve, reject) => {
      get_requset(apiHomBlogType).then((res) => {
        const { data } = res
        commit('SET_BLOGTYPE', [...data])
        resolve()
      }).catch((e) => {
        reject(e)
      })
    })
  },
  upBannerList({ commit, state }, item) {
    return new Promise((resolve, reject) => {
      upBanner(item).then((res) => {
        const { data } = res
        if (!data) reject('修改失败')
        const temp = state.bannerList
        temp[item.index] = item
        delete item.index
        commit('SET_BANNERLIST', { ...temp })
        resolve()
      }).catch((e) => {
        reject(e)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
